package com.qfedu.hello.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Objects;

/**
 * @auther asus
 * @date 2022/4/21 14:09
 *
 * MyBatis的工具类
 * 提供打开/关闭会话 提交/回滚事务 获取接口代理对象的方法
 */
public class MyBatisUtil {
    //获得SqlSession工厂
    private static SqlSessionFactory factory;
    //创建ThreadLocal绑定当前线程中的SqlSession对象
    private static final ThreadLocal<SqlSession> TL = new ThreadLocal<>();

    static {
        try {
            //在静态代码块中初始化数据源
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获得连接（从TL中获取当前线程SqlSession）
    private static SqlSession openSession(){
        SqlSession sqlSession = TL.get();
        if (Objects.isNull(sqlSession)){
            sqlSession=factory.openSession();
            TL.set(sqlSession);
        }
//        SqlSession sqlSession = factory.openSession();
        return sqlSession;
    }

    //关闭连接
    private static void closeSession(){
        SqlSession sqlSession = openSession();
        sqlSession.close();
        TL.remove();
    }

    //提交事务（提交当前线程中的SqlSession所管理的事务）
    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
        closeSession();
    }

    //回滚事务（回滚当前线程中的SqlSession所管理的事务）
    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
        closeSession();
    }

    //获得接口对象
    public static <T extends Object>T getMapper(Class<T> tClass){
        SqlSession sqlSession = openSession();
        T mapper = sqlSession.getMapper(tClass);
        return mapper;
    }
}
